package com.net.common.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.base.Strings;

/**
 * @author  on 2015/10/23.
 */
public class ServletUtil {
    public static final char PATH_SEP = '/';

    public static boolean sendRedirect(HttpServletResponse response, String url) {
        if (Strings.isNullOrEmpty(url)) {
            return false;
        }
        try {
            response.sendRedirect(url);
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String getTopmostPath(HttpServletRequest request) {
        return getTopmostPath(request.getRequestURI());
    }

    //uri is arrived from HttpServletRequest request.getRequestURI().
    public static String getTopmostPath(String uri) {
        if (Strings.isNullOrEmpty(uri) || uri.charAt(0) != PATH_SEP) {
            return "";
        }
        String str = uri.substring(1);
        boolean isStart = true;
        int length = str.length();
        StringBuilder sb = new StringBuilder("");

        for (int i = 0; i < length; i++) {
            char ch = str.charAt(i);
            if (ch == PATH_SEP) {
                if (!isStart) {
                    return sb.toString();
                }
            } else {
                isStart = false;
                sb.append(ch);
            }
        }
        return sb.toString();
    }
}
